package xyz.xiezc.mzix.common.dto;

import cn.hutool.core.lang.Assert;
import lombok.Data;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.time.temporal.ChronoUnit.MILLIS;

@Data
public class Request {

    String url;

    String method = "GET";

    Map<String, List<String>> headers = new HashMap<>();

    byte[] body;

    HttpClient.Version version = HttpClient.Version.HTTP_1_1;

    Long timeout = 30000L;

    public HttpRequest buildHttpRequest() {
        Assert.notBlank(url, "请传入url");
        Assert.notBlank(method, "请求方式， GET or POST");

        HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(url));
        headers.forEach((k, v) -> {
            for (String value : v) {
                builder.header(k, value);
            }
        });
        if (body == null || body.length == 0) {
            builder.method(method, HttpRequest.BodyPublishers.noBody());
        } else {
            builder.method(method, HttpRequest.BodyPublishers.ofByteArray(body));
        }
        builder.timeout(Duration.of(timeout, MILLIS));
        builder.version(HttpClient.Version.HTTP_1_1);
        return builder.build();
    }

}
